package com.sayice.robotconflict.game;

import com.sayice.robotconflict.config.RobotConflictConfig;
import com.sayice.robotconflict.game.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


/**
 * 游戏服务器
 *
 * @author shubing
 */
@Slf4j
@Component
public class GameServer {
    @PostConstruct
    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) {
                        channel.pipeline()
                                .addLast(new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2))
                                .addLast(new StringDecoder())
                                .addLast(new IdleStateHandler(15, 5, 0))
                                .addLast(new ConnectHandler())
                                .addLast(new PlayerHandler())
                                .addLast(new SocialHandler())
                                .addLast(new TeamHandler())
                                .addLast(new MatchHandler())
                                .addLast(new GameHandler())
                                .addLast(new LengthFieldPrepender(2))
                                .addLast(new StringEncoder());
                    }
                });
        bootstrap.bind(RobotConflictConfig.getGamePort());
        log.info("GameServer started on port: " + RobotConflictConfig.getGamePort());
    }
}
